import qs from 'qs';
import moment from 'moment';
import Post from '../../../Models/post';
import User from '../../../Models/user';
import Ucode from '../../../Models/ucode';
import Point from '../../../Models/point';
import User2User from '../../../Models/user2User';
import Money from '../../../Models/money';
import HsPay from '../../../Models/hspay';
import { getCreator, getLevel } from '../../../utils/util';
import { getPayData } from '../utils/';
const fetch = require('node-fetch');

const postEntity = new Post();
const crypto = require('crypto');
const jwt = require("jwt-simple");
const svgCaptcha = require('svg-captcha');
const userEntity = new User();
const pointEntity = new Point();
const ucodeEntity = new Ucode();
const user2UserEntity = new User2User();

const QcloudSms = require("qcloudsms_js");

// 短信应用SDK AppID
const appid = 1400158921;  // SDK AppID是1400开头

// 短信应用SDK AppKey
const appkey = "4e854f058a9bdeb53b1705774b9c9531";

// 需要发送短信的手机号码
// var phoneNumbers = ["21212313123", "12345678902", "12345678903"];

// 短信模板ID，需要在短信应用中申请
const templateId = 223053;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
//templateId 7839 对应的内容是"您的验证码是: {1}"
// 签名
const smsSign = "杭州学大经财科技有限公司";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

// 实例化QcloudSms
const qcloudsms = QcloudSms(appid, appkey);
const ssender = qcloudsms.SmsSingleSender();

function getFRandom() {
    return parseInt(Math.random()*(9999-1000+1)+1000,10) + '';
}

export function getValidateCode(req,res,next){
    let tel = req.body.tel;
    userEntity.getUser({
        tel
    },(err,user)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if(user && user._doc.passwd){
            return res.status(200).json({ code: 1, msg: '该账号已经有人注册!' });
        }
        // const ssender = qcloudsms.SmsSingleSender();
        const code = getFRandom();
        const params = [code];
        ssender.sendWithParam(86, tel, templateId, params, smsSign, "", "", function (err, res1, resData) {
            if (err) {
                console.log("err: ", err);
            } else {
                // console.log("request data: ", res1.req);
                // console.log("response data: ", resData);
                if (user && user._id) {
                    userEntity.updateUser({
                        _id: user._id,
                        code,
                    },err=>{
                        if(err){
                            return res.status(200).json({ code: 1, msg: '服务器开小差' });
                        }
                        return res.status(200).json({ code: 0, data: {} });
                    })
                } else {
                    userEntity.saveUser({
                        tel,
                        code,
                        isAuth: false
                    },err=>{
                        if(err){
                            return res.status(200).json({ code: 1, msg: '服务器开小差' });
                        }
                        return res.status(200).json({ code: 0, data: {} });
                    })
                }
            }
        }); 
    })
}

export function getLoginValidateCode(req,res,next){
    let tel = req.body.tel;
    userEntity.getUser({
        tel
    },(err,user)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if(!user || !user._doc.passwd){
            return res.status(200).json({ code: 1, msg: '该账号尚未注册!' });
        }
        
        const code = getFRandom();
        const params = [code];
        ssender.sendWithParam(86, tel, templateId, params, smsSign, "", "", function (err, res1, resData) {
            if (err) {
                console.log("err: ", err);
            } else {
                // console.log("request data: ", res1.req);
                // console.log("response data: ", resData);
                userEntity.updateUser({
                    _id: user._doc._id,
                    code
                },err=>{
                    if(err){
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    return res.status(200).json({ code: 0 });
                })
            }
        }); 
    })
}

export function getCaptcha(req,res,next){
    let uCode = req.body.uCode;
    ucodeEntity.getUcode({
        uCode
    },(err, ucode)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const codeConfig = {
            size: 5,// 验证码长度
            ignoreChars: '0o1i', // 验证码字符中排除 0o1i
            noise: 2, // 干扰线条的数量
            height: 44 
        }
        const captcha = svgCaptcha.create(codeConfig);
        const captchaText = captcha.text.toLowerCase(); //存session用于验证接口获取文字码
        if(ucode){
            ucodeEntity.updateUcode({
                _id: ucode._doc._id,
                captchaText
            }, err=>{
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0, data: captcha.data });
            })
        } else {
            const ucodeEntity = new Ucode();
            ucodeEntity.saveUcode({
                uCode,
                captchaText
            }, err=>{
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0, data: captcha.data });
            })
        }
    })
}

export function validateCaptcha(req,res,next){
    const  { uCode, captchaText, tel } = req.body;
    ucodeEntity.getUcode({
        uCode
    },(err, ucode)=>{
        if(err || !ucode){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        
        if(captchaText !== ucode._doc.captchaText){
            return res.status(200).json({ code: 1, msg: '请输入正确的验证码' });
        } else {
            userEntity.getUser({
                tel
            },(err,user)=>{
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                if(!user || !user._doc.passwd){
                    return res.status(200).json({ code: 1, msg: '该账号尚未注册!' });
                }
                return res.status(200).json({ code: 0 });
                // const code = getFRandom();
                // const params = [code];
                // ssender.sendWithParam(86, tel, templateId, params, smsSign, "", "", function (err, res1, resData) {
                //     if (err) {
                //         console.log("err: ", err);
                //     } else {
                //         // console.log("request data: ", res1.req);
                //         // console.log("response data: ", resData);
                //         userEntity.updateUser({
                //             _id: user._doc._id,
                //             code
                //         },err=>{
                //             if(err){
                //                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
                //             }
                //             return res.status(200).json({ code: 0 });
                //         })
                //     }
                // }); 
            })
        }
    })
}

export function resetPasswd(req,res,next){
    let tel = req.body.tel,
        passwd = req.body.passwd || '',
        md5 = crypto.createHash('md5'),
        code = req.body.code;
    
    passwd = md5.update(passwd).digest('hex');
    userEntity.getUser({
        tel
    },(err,user)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if(user && code !==user._doc.code){
            return res.status(200).json({ code: 1, msg: '验证码错误!' });
        }
        
        userEntity.updateUser({
            _id: user._doc._id,
            passwd,
        },err=>{
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            var expires = moment().add(7,'days').valueOf();
            var token = jwt.encode({
                _id: user._doc._id,
                avatar: user._doc.avatar,
                nickname: user._doc.nickname,
                tel: user._doc.tel,
                schoolId: user._doc.schoolId,
                exp: expires
            }, req.app.get('jwtTokenSecret'));
            return res.status(200).json({ code: 0, data: { token, user } });
        })
    })
}

export function dailySignin(req,res,next){
    const { _id } = req.user;
    pointEntity.getPoint({creatorId: _id, dayString: moment().format('YYYY-MM-DD'), desc: '每日签到'}, (err, point)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (point) {
            return res.status(200).json({ code: 1, msg: '今日已完成签到' });
        }
        userEntity.getUser({
            _id
        },(err,user)=>{
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            const point = (user._doc.point || 0) + 5;
            const leftPoint = (user._doc.leftPoint || 0) + 5;
            userEntity.updateUser({
                _id: user._doc._id,
                point,
                leftPoint
            },err=>{
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                const pointEntity = new Point();
                pointEntity.savePoint({creatorId: _id, score: 1, desc: '每日签到'}, err=>{
                    if(err){
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    return res.status(200).json({ code: 0});
                })
            })
        })
    })
}

export function reg(req,res,next){
    let tel = req.body.tel,
        passwd = req.body.passwd || '',
        code = req.body.code,
        md5 = crypto.createHash('md5');
    passwd = md5.update(passwd).digest('hex');
    userEntity.getUser({
        tel
    },(err,user)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if(user && user._doc.passwd){
            return res.status(200).json({ code: 1, msg: '该账号已经有人注册!' });
        }
        if (user._doc.code !== code) {
            return res.status(200).json({ code: 1, msg: '输入的验证码不正确!' });
        }
        userEntity.updateUser({
            _id: user._doc._id,
            passwd,
        },err=>{
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            var expires = moment().add(7,'days').valueOf();
            var token = jwt.encode({
                _id: user._doc._id,
                avatar: user._doc.avatar,
                nickname: user._doc.nickname,
                tel: user._doc.tel,
                schoolId: user._doc.schoolId,
                exp: expires
            }, req.app.get('jwtTokenSecret'));
            return res.status(200).json({ code: 0, data: { token, user: {...user._doc, level: getLevel(user.point)} } });
        })
    })
}

export function log (req, res, next) {
    let tel = req.body.tel,
        passwd = req.body.passwd || '',
        md5 = crypto.createHash('md5'),
        code = req.body.code;
    
    passwd = md5.update(passwd).digest('hex');
        
    userEntity.getUser({
        tel
    }, (err, user) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!user) {
            return res.status(200).json({ code: 1, msg: '该账号没有注册' });
        } else {
            let msg = "";
            if (req.body.passwd && passwd !== user._doc.passwd) {
                msg = '账号或密码不对';
            }
            if (code && code !== user._doc.code) {
                msg = '验证码不正确';
            }
            if (msg) {
                return res.status(200).json({ code: 1, msg });
            }
            var expires = moment().add(7, 'days').valueOf();
            var token = jwt.encode({
                _id: user._doc._id,
                avatar: user._doc.avatar,
                nickname: user._doc.nickname,
                tel: user._doc.tel,
                schoolId: user._doc.schoolId,
                exp: expires
            }, req.app.get('jwtTokenSecret'));
            return res.status(200).json({ code: 0, data: { token, user: {...user._doc, level: getLevel(user.point)} } });
        }
    })
}

export function adminlog (req, res, next) {
    let tel = req.body.tel,
        passwd = req.body.passwd || '',
        md5 = crypto.createHash('md5'),
        code = req.body.code;
    
    if (!['15867164299'].includes(tel)) {
        return res.status(200).json({ code: 1, msg: '您不是管理员，无法登陆' });
    }
    
    passwd = md5.update(passwd).digest('hex');
        
    userEntity.getUser({
        tel
    }, (err, user) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!user) {
            return res.status(200).json({ code: 1, msg: '该账号没有注册' });
        } else {
            let msg = "";
            if (req.body.passwd && passwd !== user._doc.passwd) {
                msg = '账号或密码不对';
            }
            if (code && code !== user._doc.code) {
                msg = '验证码不正确';
            }
            if (msg) {
                return res.status(200).json({ code: 1, msg });
            }
            var expires = moment().add(7, 'days').valueOf();
            var token = jwt.encode({
                _id: user._doc._id,
                avatar: user._doc.avatar,
                nickname: user._doc.nickname,
                tel: user._doc.tel,
                schoolId: user._doc.schoolId,
                exp: expires
            }, req.app.get('jwtTokenSecret'));
            return res.status(200).json({ code: 0, data: { token, user: {...user._doc, level: getLevel(user.point)} } });
        }
    })
}

export function updateUserInfo(req,res,next){
    const creator = getCreator(req.user);
    userEntity.getUser({
        _id: creator._id
    },(err,user)=>{
        if(err){
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!user) {
            return res.status(200).json({ code: 1, msg: '服务器开小差1' });
        }
        const params = { _id: creator._id };
        ['avatar', 'birthday', 'grade', 'gender', 'college', 'major', 'nickname', 'schoolId', 'idImgs', 'bgImage', 'sId', 'realName'].forEach(c=>{
            if(req.body[c]) {
                params[c] = req.body[c]
            }
        })
        userEntity.updateUser(params,(err)=>{
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            userEntity.getUser({
                _id: creator._id
            },(err,users)=>{
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                if (!users) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差2' });
                }
                var expires = moment().add(7,'days').valueOf();
                var token = jwt.encode({
                    _id: users._id,
                    avatar: users.avatar,
                    nickname: users.nickname,
                    tel: users.tel,
                    schoolId: users.schoolId,
                    exp: expires
                }, req.app.get('jwtTokenSecret'));
                return res.status(200).json({ code: 0, data: { token, user: users } });
            })
        })
        
    })
}

export function watchUser(req,res,next){
    const { user2Obj, status } = req.body;
    const userObj = getCreator(req.user);
    const userId = userObj._id;
    const obj = {userId, user2Id: user2Obj._id}
    if (user2Obj._id === userId) {
        return res.status(200).json({ code: 1, msg: '不能关注自己' });
    }
    if (status) {
        // status === 1
        user2UserEntity.getUser2User(obj, (err, user2User) => {
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            if (!user2User) {
                return res.status(200).json({ code: 1, msg: '尚未关注该用户' });
            }
            user2UserEntity.removeUser2Users([user2User._id], (err) => {
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            })
        })
    } else {
        user2UserEntity.getUser2User(obj, (err, user2User) => {
            if(err){
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            if (user2User) {
                return res.status(200).json({ code: 1, msg: '已经关注该用户' });
            }
            obj.userObj = userObj;
            obj.user2Obj = user2Obj;
            const user2UserEntity = new User2User();
            user2UserEntity.saveUser2User(obj, (err) => {
                if(err){
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            })
        })
    }
}


export function user(req,res,next){
    const user = req.user;
    userEntity.getUser({
        tel: user.tel
    }, (err, user) => {
        if (user) {
            return res.status(200).json({ code: 0, data: user });
        } else {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
    });
}

export function viewUserInfo(req,res,next){
    const {userId} = req.body;
    userEntity.getUser({
        _id: userId
    }, (err, user) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!user) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
            
        } 
        const { nickname, avatar, college, grade, bgImage, major, gender, point } = user;
        const userInfo = { nickname, avatar, college, grade, bgImage, major, gender, level: getLevel(point) }
        postEntity.getPosts({creatorId: userId, type: 0}, (err, posts, total, hasMore) => {
            userInfo.posts = posts
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0, data: userInfo });
        })
    });
}

export function getUsers(req, res, next) {
    const {  ...query } = req.body;
    userEntity.getUsers(query, (err, users, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: users, total, hasMore } });
    })
}

// export function getUser(req, res, next) {
//     userEntity.getUser({}, (err, users) => {
//         if (err) {
//             return res.status(200).json({ code: 1, msg: '服务器开小差' });
//         }
//         return res.status(200).json(users);
//     })
// }

export function getAllUsers(req, res, next) {
    userEntity.getAllUsers({}, (err, users) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: users.filter((user) => user.name !== 'admin') });
    })
}

export function updateUser(req, res, next) {
    const {  ...user } = req.body;
    const userEntity = new User();
    if (!user._id) {
        userEntity.saveUser(user, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    } else {
        userEntity.updateUser(user, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    }
}

export function removeUsers(req, res, next) {
    const userIds = req.body.userIds;
    const userEntity = new User();

    userEntity.removeUsers(userIds, (err, user) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function chargeUser(req, res, next) {
    const { occur_balance, channel_id } = req.body;
    const body = getPayData('充值', occur_balance, '充值', channel_id, "http://111.231.87.118:3001/api/getChargeCallback")
    // fetch('http://uat.epay.hscloud.cn:6101/eis/yunpay/epay_wallet_pay', {method: 'POST', body, headers: {
    fetch('http://121.43.72.206:6201/eis/yunpay/epay_wallet_pay', {method: 'POST', body, headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }})
    .then(res => res.json())
    .then(json => {
        console.log(json, 888)
        const hsBack = json.data[0] || {};
        const hsPayEntity = new HsPay();
        hsPayEntity.saveHsPay({},err=>{
            if (err) {
                return res.status(200).json({ code: 1, data: 服务器开小差 });
            }
            return res.status(200).json({ code: 0, data: hsBack.view });
        });
    });
}

export function getChargeCallback(req, res, next) {
    const { occur_balance } = req.body;
    const userEntity = new User();
    hsPayEntity.getHsPay({},(err, hspay)=>{
        if (err) {
            return res.status(200).json({ code: 1, data: 服务器开小差 });
        }
        return res.status(200).json({ code: 0, data: hsBack.view });
    })
    userEntity.getUser({
        _id: hspay.errandId
    }, (err, user) => {
        if (err || !user) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const newmoney = (user.money || 0) + Number(occur_balance);
        const money = {
            fromUserId: 'system',
            toUserId: creator._id,
            errandId: '',
            money: occur_balance,
            msg: '充值',
            payTool: 1,
        }
        const moneyEntity = new Money();
        moneyEntity.saveMoney(money, err=>{
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            userEntity.updateUser({_id: hspay.errandId, money: newmoney }, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            });
        })
    });
}

export function getServiceUser(req, res, next) {
    userEntity.getUser({
        tel: 8888
    }, (err, user) => {
        if (err || !user) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const { _id, avatar, nickname } = user;
        return res.status(200).json({ code: 0, data: {_id, avatar, nickname} });
    });
}



